//
//  Movable.m
//  DnImageCropper
//
//  Created by Ngoc on 10/11/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "ResizableView.h"
@interface ResizableView (Private)
-(CGRect) getNewRectForFreedomMethodWithRect:(CGRect) oldRect resizePosition:(ResizePosition) resizePosition fromPoint  :(CGPoint) fromPoint movePoint:(CGPoint) movePoint;
-(CGRect) getNewRectForScaleMethodWithRect:(CGRect) oldRect resizePosition:(ResizePosition) resizePosition fromPoint:(CGPoint) fromPoint movePoint:(CGPoint) movePoint scale:(CGSize) scale;
-(CGRect) standardizeRect:(CGRect) oldRect ratio:(CGSize) scale;
-(void) hideGrid;

-(CGRect) getNewRectWithMoveFrom:(CGPoint) fromPoint movePoint:(CGPoint) movePoint;
-(void) defaultInit;
-(BOOL) touchInWindow:(UITouch*)touch;
-(BOOL) touchInPosition:(UITouch*)touch;
-(void) updateActionRect;
-(void) staticVariableInit;
@end


@implementation ResizableView
@synthesize minWidth, minHeight, borderWidth, selectionRect, resizeMethod = userResizeMethod, rotationDelegate=_rotationDelegate, rotation =_rotation;
@dynamic displayArea, action;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultInit];
    }
    
    return self;
}
-(id) init
{
    self = [super init];
    if(self)
    {
        [self defaultInit];
    }
    return self;
}
-(id) initWithFrame:(CGRect)frame minWidth:(int) minW minHeight:(int) minH centerPoint:(CGPoint) centerPoint
{
    self = [super initWithFrame:frame];
    if (self) {
        minWidth = minW;
        minHeight = minH;
        selectionRect = CGRectZero;
        selectionRect.size.width = minWidth;
        selectionRect.size.height = minHeight;
        selectionRect.origin = CGPointMake(centerPoint.x -minWidth/2, centerPoint.y - minHeight/2);
        [self staticVariableInit];
    }
    return self;
}

-(void) staticVariableInit
{
    _isTest = NO;
    rowCount = 3;
    columnCount =rowCount;
    gridColorAlpha =1.0;
    self.backgroundColor = [UIColor clearColor];
    self.borderWidth = 1.0;
    [self setUserInteractionEnabled:YES];
    padding = 1.5;
    cornerImage = [UIImage imageNamed:@"cornerCropRec.png"];
    edgeImage = [UIImage imageNamed:@"edgeCropRec.png"];
    hozEdgeImage = [UIImage imageNamed:@"edgeCropRec-hoz.png"];
    displayRect = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
    
    UIRotationGestureRecognizer *rotateGesture = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotate:)];
    
    //UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    
    [self addGestureRecognizer:rotateGesture];
    //[self addGestureRecognizer:pinchGesture];
    
    _ghostView =[[UIView alloc]init];
}
-(void) pinch:(id) sender
{
    if (userResizeMethod != Straighten) {
        
        CGRect tempRect = selectionRect;
        float scale = [(UIPinchGestureRecognizer*) sender scale];
        tempRect.size.width *=scale;
        tempRect.size.height *=scale;
        
        if (tempRect.size.width> minWidth && tempRect.size.height>minHeight) {
            if (tempRect.size.width< displayRect.size.width && tempRect.size.height<displayRect.size.height) {
                tempRect.origin.x = (displayRect.origin.x + displayRect.size.width/2)-tempRect.size.width/2;
                tempRect.origin.y = (displayRect.origin.y + displayRect.size.height/2)-tempRect.size.height/2;
                
                CGFloat minDimension = MIN(displayRect.size.width, displayRect.size.height);
                float subtense = sqrtf(powf(tempRect.size.width, 2)+powf(tempRect.size.height, 2));
                
                if (subtense<minDimension) {
                    selectionRect = tempRect;
                    [self setNeedsDisplay];
                }
            }
        }
        
        
    }
}
-(void) rotate:(id) sender
{
    
    if (userResizeMethod==Straighten) {
        CGFloat rotation = 0.0- (_lastRotationRadian - [(UIRotationGestureRecognizer*)sender rotation]);
        _rotation += rotation;
        if ([(UIRotationGestureRecognizer*) sender state] == UIGestureRecognizerStateEnded) {
            _lastRotationRadian =rotation;
            [self hideGrid];
            return;
        }
        
        
        [_rotationDelegate rotationChange:rotation];
        CGAffineTransform currentTransform = _ghostView.transform;;
        CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
        [_ghostView setTransform:newTransform];
        [self setTransform:newTransform];
        _lastRotationRadian = [(UIRotationGestureRecognizer*)sender rotation];
        float angle =  atan2(_ghostView.transform.b, _ghostView.transform.a);
        float sint, cost, h1, h2,hh,ww;
        CGRect newRect = displayRect;
        angle = fabsf(angle);
        if(angle>= M_PI_2 && angle<M_PI)
        {
            angle = M_PI-angle;
        }
        
        sint =  sinf(angle);
        cost = cosf(angle);
        h1 = newRect.size.height * newRect.size.height / (newRect.size.width * sint + newRect.size.height * cost);
        h2 = newRect.size.height * newRect.size.width / (newRect.size.width * cost + newRect.size.height * sint);
        
        hh = MIN(h1, h2);
        ww = hh * newRect.size.width / newRect.size.height;
        
        newRect.size.height = hh;
        newRect.size.width = ww;
        
        newRect.origin.x = CGRectGetMidX(displayRect) - newRect.size.width/2;
        newRect.origin.y = CGRectGetMidY(displayRect)- newRect.size.height/2;
        if (CGRectContainsRect(displayRect, newRect)) {
            selectionRect = newRect;
        }
        
        
        [self setNeedsDisplay];
    }
    else _lastRotationRadian =0.0;
}
-(void) resetAll
{
    _lastRotationRadian =0;
    _rotation =0;
    _ghostView.transform = CGAffineTransformIdentity;
    self.transform = CGAffineTransformIdentity;
    selectionRect = CGRectMake(0, 0, minWidth, minHeight);
}
-(void) setAction:(Action)action
{
    _action = action;
    
}
-(Action) getAction
{
    return _action;
}
-(void) defaultInit
{
    [self staticVariableInit];
    //int n = 6;
    minWidth = 3*cornerImage.size.height;
    minHeight = 3*cornerImage.size.height;
    // selectionRect = CGRectMake(self.center.x - (n/2)*cornerImage.size.width, self.center.y-(n/2)*cornerImage.size.height, n*cornerImage.size.width, n*cornerImage.size.height);
    
    
}
-(void) setDisplayArea:(CGRect)displayArea
{
    displayRect = displayArea;
    switch (_action) {
        case ActionCrop:
        {
            selectionRect = CGRectMake(CGRectGetMidX(displayArea)-minWidth/2, CGRectGetMidY(displayArea)-minHeight/2, minWidth, minHeight);
            selectionRect = [self standardizeRect:selectionRect ratio:[self getRatioForResizeMethod:userResizeMethod]];
//            if (userResizeMethod == Straighten) {
//                int pad = 3;
//                selectionRect = CGRectMake(displayRect.origin.x+pad, displayRect.origin.y+pad, displayRect.size.width-2*pad, displayRect.size.height-2*pad);
//            }
            break;
        }   
        default:
            break;
    }
    
    [self setNeedsDisplay];
}
-(CGRect) getDisplayArea
{
    return displayRect;
}
-(BOOL) isCanMoveAround
{
    BOOL isCanMove = YES;
    if (userResizeMethod == Straighten) {
        isCanMove = NO;
    }
    return isCanMove;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self superview] bringSubviewToFront:self ];
    
    UITouch* touch = [touches anyObject];
    lastPoint = [touch locationInView:self.superview];
    if(isDrawGrid) 
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doTimer) object:nil];
        gridColorAlpha = 1.0;
    }
    isDrawGrid = YES;
    BOOL touchInWindow = [self touchInWindow:touch];
    if([self isCanMoveAround]  && touchInWindow)
    {
        userResizePosition = [self touchInPosition:touch];  
        if(None == userResizePosition) userMoving = touchInWindow;
    }
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGRect newRect;
    CGPoint point = [[touches anyObject] locationInView:self.superview];
    if ([self isCanMoveAround]) {
        if(userMoving)
        {
            CGPoint distance = CGPointMake(point.x - lastPoint.x, point.y - lastPoint.y); 
            float oldX = selectionRect.origin.x;
            float oldY = selectionRect.origin.y;
            int x = oldX + distance.x;
            int y = oldY + distance.y;
            
            newRect = CGRectMake(x, y, selectionRect.size.width, selectionRect.size.height);
        }            
        
        if(None != userResizePosition)
        {
            newRect = [self getNewRectWithMoveFrom:lastPoint movePoint:point];
            
        }
        if (newRect.size.width >= self.minWidth && newRect.size.height >= self.minHeight &&
            CGRectContainsRect(displayRect, newRect))
        {
            selectionRect = newRect;
           
        }
    }
    lastPoint = point;
    [self setNeedsDisplay];
    
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    userMoving = NO;
    userResizePosition = None;
    [self hideGrid];
}
-(void) hideGrid
{
    [self performSelector:@selector(doTimer) withObject:nil afterDelay:1.5];
}
// Draw grid with animation
-(void) doTimer
{
    if(gridColorAlpha <= 0)
    {
        isDrawGrid = NO;
        gridColorAlpha = 1.0;
    }
    else 
    {
        gridColorAlpha -=0.1;
        [self performSelector:@selector(doTimer) withObject:nil afterDelay:0.1];
    }
    [self setNeedsDisplay];
    
}
- (void)drawRect:(CGRect)rect
{
    
    
    CGContextRef currentContex = UIGraphicsGetCurrentContext();
    
    
    // Rotate
    if (userResizeMethod==Straighten) {
        CGContextSaveGState(currentContex);
        //CGContextTranslateCTM(currentContex,0, self.frame.size.height);
        //CGContextScaleCTM(currentContex, 1.0, -1.0);
        CGContextTranslateCTM(currentContex, CGRectGetMidX(selectionRect) , CGRectGetMidY(selectionRect));
        CGContextRotateCTM(currentContex,-_rotation);
        CGContextTranslateCTM(currentContex, -CGRectGetMidX(selectionRect), -CGRectGetMidY(selectionRect));
    }
    
    
    CGContextSaveGState(currentContex);
    CGContextSetRGBStrokeColor(currentContex, 0.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(currentContex);
    CGContextSetGrayFillColor(currentContex, 0.0f, 0.4);
    CGContextAddRect(currentContex, self.frame);
    CGContextFillPath(currentContex);
    CGContextRestoreGState(currentContex);
    
    //Draw Selection Rect
    CGContextSetLineWidth(currentContex, padding);    
    CGContextSetStrokeColorWithColor(currentContex,[UIColor whiteColor].CGColor);
    CGContextClearRect(currentContex, selectionRect);
    CGContextAddRect(currentContex, selectionRect);
    CGContextStrokePath(currentContex);
    
    
    // Draw grid
    // CGContextSetStrokeColorWithColor(currentContex, [UIColor redColor].CGColor);
    
    if(isDrawGrid)
    {
        CGContextSaveGState(currentContex);
        CGContextSetLineWidth(currentContex, 0.4);
        CGContextSetRGBStrokeColor(currentContex, 1.0, 1.0, 1.0, gridColorAlpha);
        int cDistance= selectionRect.size.width/columnCount;
        for (int col=1; col<rowCount; col++) {
            CGContextMoveToPoint(currentContex, selectionRect.origin.x + col*cDistance, selectionRect.origin.y+selectionRect.size.height+self.borderWidth/2);
            CGContextAddLineToPoint(currentContex, selectionRect.origin.x + col*cDistance, selectionRect.origin.y);
            CGContextStrokePath(currentContex);
        }
        int rDistance= selectionRect.size.height/rowCount;
        for (int row=1; row<columnCount; row++) {
            CGContextMoveToPoint(currentContex, selectionRect.origin.x, selectionRect.origin.y + row*rDistance);
            CGContextAddLineToPoint(currentContex, selectionRect.origin.x+selectionRect.size.width+self.borderWidth/2, selectionRect.origin.y + row*rDistance);
            CGContextStrokePath(currentContex);
        }
        CGContextRestoreGState(currentContex);
    }
    
    
    
    switch (_action) {
        case ActionCrop:
        {
            if(userResizeMethod == Straighten)
            {
                CGContextRestoreGState(currentContex);
            }
            else
            {
                // Draw action image
                [self updateActionRect];
                CGContextDrawImage(currentContex, topLeftRect, cornerImage.CGImage);
                CGContextDrawImage(currentContex, topRightRect, cornerImage.CGImage);
                CGContextDrawImage(currentContex, bottomRightRect, cornerImage.CGImage);
                CGContextDrawImage(currentContex, bottomLeftRect, cornerImage.CGImage);
                
                if (userResizeMethod == FreeDom) {
                    if (_isTest) {
                        
                    
                    CGContextStrokeRect(currentContex, middleTopRect);
                    CGContextStrokeRect(currentContex, middleBottomRect);
                    CGContextStrokeRect(currentContex, middleRightRect);
                    CGContextStrokeRect(currentContex, middleLeftRect);
                    }
                    int widthMiddle = edgeImage.size.width;
                    int heightMiddle = edgeImage.size.height;
                    int hoz = selectionRect.size.width/2;
                    int ver = selectionRect.size.height/2;
                    
                    CGRect middleTopRect2,middleBottomRect2,middleLeftRect2,middleRightRect2;
                    
                    // Draw rectangles. Need update
                    middleTopRect2 = CGRectMake(selectionRect.origin.x+hoz-heightMiddle/2, selectionRect.origin.y-widthMiddle/2, heightMiddle, widthMiddle);
                    middleBottomRect2 = CGRectMake(middleTopRect.origin.x, selectionRect.origin.y+selectionRect.size.height-widthMiddle/2, heightMiddle, widthMiddle);
                    
                    middleLeftRect2 = CGRectMake(selectionRect.origin.x-widthMiddle/2, selectionRect.origin.y+ver-heightMiddle/2, widthMiddle, heightMiddle);
                    middleRightRect2 = CGRectMake(selectionRect.origin.x + selectionRect.size.width-widthMiddle/2, middleLeftRect.origin.y, widthMiddle, heightMiddle);
                    
                    CGContextDrawImage(currentContex, middleTopRect2, hozEdgeImage.CGImage);
                    CGContextDrawImage(currentContex, middleBottomRect2, hozEdgeImage.CGImage);
                    
                    CGContextDrawImage(currentContex, middleRightRect2, edgeImage.CGImage);
                    CGContextDrawImage(currentContex, middleLeftRect2, edgeImage.CGImage);
                    
                }
            }
            
            
            break;
        }
        default:
            break;
    }
    
    if (_isTest) {
        
        
        // Test
        CGContextSetLineWidth(currentContex, 1);
        if (userResizeMethod !=Straighten) {
            
            
            CGContextStrokeRect(currentContex, topLeftRect);
            CGContextStrokeRect(currentContex, topRightRect);
            CGContextStrokeRect(currentContex, bottomRightRect);
            CGContextStrokeRect(currentContex, bottomLeftRect);
        }
        if (label) {
            [label removeFromSuperview];
        }
        else label = [[UILabel alloc] init];
        NSString * string = [NSString stringWithFormat:@"%@, Ratio: %f",NSStringFromCGSize(selectionRect.size), (CGFloat) (selectionRect.size.width/selectionRect.size.height)];
        label.text = string;
        CGSize stringSize = [label.text sizeWithFont:label.font];
        label.frame = CGRectMake(selectionRect.origin.x, selectionRect.origin.y-2*stringSize.height,stringSize.width, stringSize.height);    
        [self addSubview:label];
        // slow speed
        //[string drawAtPoint:CGPointMake(selectionRect.origin.x+5, selectionRect.origin.y-5) withFont:[UIFont fontWithName:@"Arial" size:15]];
    }
    
}
-(BOOL) touchInWindow:(UITouch*)touch
{
    CGPoint point = [touch locationInView:self];
    CGRect selectionView = CGRectMake(selectionRect.origin.x-cornerImage.size.width/2, selectionRect.origin.y-cornerImage.size.height/2, selectionRect.size.width+cornerImage.size.width, selectionRect.size.height+cornerImage.size.height);
    if(CGRectContainsPoint(selectionView, point))
    {
        return YES;
    }
    else {
        return NO;
    }
    
}

-(BOOL) touchInPosition:(UITouch*)touch
{
    CGPoint point = [touch locationInView:self];
    ResizePosition position = None;
    if(CGRectContainsPoint(bottomRightRect, point))
    {
        position = BottomRightCorner;
    }
    else if(CGRectContainsPoint(bottomLeftRect, point))
    {
        position = BottomLeftCorner;
    }
    else if(CGRectContainsPoint(topLeftRect, point))
    {
        position = TopLeftCorner;
    }
    else if(CGRectContainsPoint(topRightRect, point))
    {
        position = TopRightCorner;
    }
    if (userResizeMethod == FreeDom) {
        
        if(CGRectContainsPoint(middleTopRect, point))
        {
            position = TopEdgeMiddle;
        }
        else if(CGRectContainsPoint(middleBottomRect, point))
        {
            position = BottomEdgeMiddle ;
        }
        else if(CGRectContainsPoint(middleLeftRect, point))
        {
            position = LeftEdgeMiddle;
        }
        else if(CGRectContainsPoint(middleRightRect, point))
        {
            position = RightEdgeMiddle;
        }
    }
    return position;
}
-(void) updateActionRect
{
    if (_action == ActionCrop) {
        
        
        int widthCorner = cornerImage.size.width;
        int heightCorner = cornerImage.size.height;
        
        // int widthMiddle = edgeImage.size.width;
        int heightMiddle = edgeImage.size.height;
        
        bottomRightRect = CGRectMake(selectionRect.origin.x+selectionRect.size.width-widthCorner/2, selectionRect.origin.y+selectionRect.size.height-heightCorner/2, widthCorner, heightCorner);
        bottomLeftRect = CGRectMake(selectionRect.origin.x-widthCorner/2, bottomRightRect.origin.y, widthCorner, heightCorner);
        
        topLeftRect = CGRectMake(bottomLeftRect.origin.x, selectionRect.origin.y-heightCorner/2, widthCorner, heightCorner);
        topRightRect = CGRectMake(bottomRightRect.origin.x, topLeftRect.origin.y, widthCorner, heightCorner);
        
        int hoz = selectionRect.size.width/2;
        int ver = selectionRect.size.height/2;
        //    
        //    middleTopRect = CGRectMake(selectionRect.origin.x+hoz-heightMiddle/2, selectionRect.origin.y-widthMiddle/2, heightMiddle, widthMiddle);
        //    middleBottomRect = CGRectMake(middleTopRect.origin.x, middleTopRect.origin.y+selectionRect.size.height, heightMiddle, widthMiddle);
        //    
        //    middleLeftRect = CGRectMake(selectionRect.origin.x-widthMiddle/2, selectionRect.origin.y+ver-heightMiddle/2, widthMiddle, heightMiddle);
        //    middleRightRect = CGRectMake(middleLeftRect.origin.x + selectionRect.size.width, middleLeftRect.origin.y, widthMiddle, heightMiddle);
        
        if (userResizeMethod == FreeDom) {
            
            middleTopRect = CGRectMake(selectionRect.origin.x+hoz-heightMiddle/2, topLeftRect.origin.y , heightMiddle    , heightMiddle/2);
            middleBottomRect = CGRectMake(middleTopRect.origin.x,(bottomLeftRect.origin.y+bottomLeftRect.size.height)-heightMiddle/2, heightMiddle, heightMiddle/2);
            
            middleLeftRect = CGRectMake(topLeftRect.origin.x, selectionRect.origin.y+ver-heightMiddle/2, heightMiddle/2, heightMiddle);
            middleRightRect = CGRectMake((topRightRect.origin.x+topRightRect.size.width)-heightMiddle/2, middleLeftRect.origin.y, heightMiddle/2, heightMiddle);
        }
    }
    
}
-(CGRect) getNewRectWithMoveFrom:(CGPoint) fromPoint movePoint:(CGPoint)movePoint
{
    CGRect newRect;
    switch (userResizeMethod) {  
        case FreeDom:
        {
            newRect = [self getNewRectForFreedomMethodWithRect: selectionRect resizePosition: userResizePosition  fromPoint:fromPoint movePoint:movePoint];
            break;
        }
        default:
        {
            CGSize scale = [self getRatioForResizeMethod:userResizeMethod];
            newRect = [self  getNewRectForScaleMethodWithRect:selectionRect resizePosition:userResizePosition fromPoint:fromPoint movePoint:movePoint scale:scale];
            break;
            
        }
    }
    return newRect;
}

-(CGRect) getNewRectForFreedomMethodWithRect:(CGRect) oldRect resizePosition:(ResizePosition) resizePosition fromPoint  :(CGPoint) fromPoint movePoint:(CGPoint) movePoint
{
    CGRect newRect = oldRect;
    CGPoint distance = CGPointMake(movePoint.x - fromPoint.x, movePoint.y - fromPoint.y); 
    switch (resizePosition)
    {
        case BottomRightCorner:
        {
            newRect.size.width = oldRect.size.width + distance.x;
            newRect.size.height = oldRect.size.height + distance.y;
            
            break;
        }
        case TopLeftCorner:
        {
            newRect.size.width = oldRect.size.width - distance.x;
            newRect.size.height = oldRect.size.height - distance.y;
            newRect.origin.x+=distance.x;
            newRect.origin.y+=distance.y;
            
            break;            
        }
        case BottomLeftCorner:
        {            
            newRect.size.width = oldRect.size.width - distance.x;
            newRect.size.height = oldRect.size.height + distance.y;
            newRect.origin.x+=distance.x;
            
            break;
        }   
        case TopRightCorner:
        {
            newRect.size.width = oldRect.size.width + distance.x;
            newRect.size.height = oldRect.size.height - distance.y;
            newRect.origin.y+=distance.y;
            
            break;            
        }
        case TopEdgeMiddle:
        {
            newRect.size.height -= distance.y;
            newRect.origin.y+=distance.y;
            
            break;
        }
        case BottomEdgeMiddle:
        {
            newRect.size.height += distance.y;
            
            break;
        }
        case LeftEdgeMiddle:
        {
            newRect.size.width -= distance.x;
            newRect.origin.x+=distance.x;
            
            break;
        }
        case RightEdgeMiddle:
        {
            newRect.size.width += distance.x;
            
            break;
        }   
        default:
        {
            return newRect;
        }            
    }
    
    return newRect;
}


-(CGRect) getNewRectForScaleMethodWithRect:(CGRect)oldRect resizePosition:(ResizePosition)resizePosition fromPoint:(CGPoint)fromPoint movePoint:(CGPoint)movePoint scale:(CGSize)scale
{
    CGPoint distance = CGPointMake(movePoint.x - fromPoint.x, movePoint.y - fromPoint.y); 
    CGRect newRect = oldRect;
    CGFloat length = sqrtf(powf(movePoint.x-fromPoint.x, 2) + powf(movePoint.y-fromPoint.y, 2));
    CGFloat x, y;
    if (scale.width> scale.height) {
        y = length;
        x = (scale.width/scale.height)*y;
    }
    else 
    {
        x = length;
        y = (scale.height/scale.width)*x;
    }
    switch (resizePosition)
    {
        case BottomRightCorner:
        {       
            if (distance.x>=0 && distance.y >=0) {
                newRect.size.width += x;
                newRect.size.height += y;
            }
            else
            {
                newRect.size.width -= x;
                newRect.size.height -= y;
            }
            
            break;
        }
        case TopLeftCorner:
        {
            if (distance.x<=0 && distance.y <=0) {
                newRect.size.width += x;
                newRect.size.height += y;
                
                newRect.origin.x -=x;
                newRect.origin.y -=y;
            }
            else
            {
                newRect.size.width -= x;
                newRect.size.height -= y;
                
                newRect.origin.x +=x;
                newRect.origin.y +=y;
            }
            
            break;            
        }
        case BottomLeftCorner:
        {   
            if (distance.x <= 0 && distance.y >=0) {
                newRect.size.width += x;
                newRect.size.height += y;
                newRect.origin.x -= x;
            }
            else 
            {
                newRect.size.width -= x;
                newRect.size.height -= y;
                newRect.origin.x += x;
            }
            break;
        }   
        case TopRightCorner:
        {
            if (distance.x >=0 && distance.y <=0) {
                newRect.size.width +=x;
                newRect.size.height +=y;
                newRect.origin.y -=y;
            }
            else
            {
                newRect.size.width -=x;
                newRect.size.height -=y;
                newRect.origin.y +=y;
            }
            break;            
        } 
        default:
        {
            return newRect;
        }            
    }
    
    return newRect;    
}
-(CGSize) getRatioForResizeMethod:(ResizeMethod) resizeMethod
{
    CGSize scale=CGSizeZero;
    switch (resizeMethod) {
            
        case S3X4:
        {
            scale.width = 3;
            scale.height =4;
            
            break;
        }
        case S4X3:
        {
            scale.width = 4;
            scale.height = 3;
            break;
        }
        case S1X1:
        {
            scale.width = 1;
            scale.height =1;
            break;
        }
            
        case S3X2:
        {
            scale.width = 3;
            scale.height =2;
            break;
        }
        case S4X6:
        {
            scale.width = 4;
            scale.height =6;
            break;
        }    
        case S3X5:
        {
            scale.width = 3;
            scale.height =5;
            break;
        }
        case S5X3:
        {
            scale.width = 5;
            scale.height =3;
            break;
        }   
        case S5X7:
        {
            scale.width = 5;
            scale.height =7;
            break;
        }
        case S7X5:
        {
            scale.width = 7;
            scale.height =5;
            break;
        }   
        case S4X5:
        {
            scale.width = 4;
            scale.height =5;
            break;
        }
        case S5X4:
        {
            scale.width = 5;
            scale.height =4;
            break;
        }
        case S16X9:
        {
            scale.width = 16;
            scale.height =9;
            break;
        }
        default:
        {
            scale.width = 1;
            scale.height = 1;
            break;
        }
    }
    return scale;
}
-(void) changeResizeMethod:(ResizeMethod) resizeMethod
{
    userResizeMethod = resizeMethod;
    if (userResizeMethod == Straighten) {
        int pad = 3;
        selectionRect = CGRectMake(displayRect.origin.x+pad, displayRect.origin.y+pad, displayRect.size.width-2*pad, displayRect.size.height-2*pad);
    }
    else
    {
    CGSize scale = CGSizeZero;
    scale = [self getRatioForResizeMethod:userResizeMethod];        
    selectionRect = [self standardizeRect:selectionRect ratio:scale];       
    }
    
}
-(CGRect) standardizeRect:(CGRect) oldRect ratio:(CGSize) scale
{
    CGRect newRect = oldRect;
    
    if (oldRect.size.width<oldRect.size.height) {
        newRect.size.height = (scale.height/scale.width) * newRect.size.width; 
    }
    else newRect.size.width = (scale.width/scale.height) *newRect.size.height;
    
    
    if (newRect.size.width< minWidth || newRect.size.height<minHeight) {
        
        if (scale.width>scale.height) {
            newRect.size.height = minHeight;
            newRect.size.width = (scale.width/scale.height) *newRect.size.height;
        }
        else
        {
            newRect.size.width = minWidth;
            newRect.size.height = (scale.height/scale.width) * newRect.size.width;
        }
    }
    return newRect;    
}

- (void)dealloc
{
    [super dealloc];
}

@end
